package com.lzm.back.service;

import com.lzm.back.entity.Event;
import com.lzm.back.entity.EventCategory;
import com.lzm.back.entity.EventCategoryRelation;
import com.lzm.back.mapper.EventCategoryRelationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

@Service
public class EventCategoryRelationService {

    @Autowired
    private EventCategoryRelationMapper relationMapper;

    public List<EventCategoryRelation> searchRelations(String categoryName) {
        List<EventCategoryRelation> list = relationMapper.selectByCategoryName(categoryName);
        System.out.println(list);
        list.forEach(item -> {
            if (item.getEventNames() == null) {
                item.setEventNames(Collections.emptyList());
            }
        });
        return list;
    }

    public List<EventCategory> getAllCategories() {
        return relationMapper.selectAllCategories();
    }

    public List<Event> getAllEvents() {
        return relationMapper.selectAllEvents();
    }

    public List<Long> getEventIdsByCategoryId(Long categoryId) {
        return relationMapper.selectEventIdsByCategoryId(categoryId);
    }

    @Transactional
    public void saveRelation(Long categoryId, List<Long> eventIds) {
        // 删除旧关联
        relationMapper.deleteByCategoryId(categoryId);
        // 插入新关联
        if (!eventIds.isEmpty()) {
            relationMapper.batchInsert(categoryId, eventIds);
        }
    }

    public void deleteRelation(Long id) {
        relationMapper.deleteByPrimaryKey(id);
    }

    public void batchDeleteRelations(List<Long> ids) {
        relationMapper.batchDelete(ids);
    }
}